<template>
	<view class="container">
		<view class="step_one">
			<view class="popup_group">

				<view class="popup_group_item">
					<view class="popup_group_item_label">钓塘名称</view>
					<view class="popup_group_item_value"><input v-model="setFormData.store_name" type="text" maxlength="9" value="" placeholder="最长9个字" /></view>
				</view>
				
				<view class="popup_group_item">
					<view class="popup_group_item_label">每条鱼最大斤数</view>
					<view class="popup_group_item_value"><input v-model="setFormData.maxWeightPerFsh" type="digit" maxlength="5" placeholder="用于回鱼称重校验" /></view>
				</view>
				
				<view class="popup_group_item">
					<view class="popup_group_item_label">每条鱼最小斤数</view>
					<view class="popup_group_item_value"><input v-model="setFormData.minWeightPerFsh" type="digit" maxlength="5" placeholder="用于回鱼称重校验" /></view>
				</view>

				<view class="popup_group_item">
					<view class="popup_group_item_label">钓塘是否分多个区</view>
					<view class="popup_group_item_value">
						<radio-group @change="onpartitionModeChange($event)" style="display: flex;">
							<label style="display: flex;">
								<view><radio value=0 :checked="0==setFormData.partitionMode" /></view>
								<view>不分区</view>
							</label>
							<label style="display: flex; margin-left: 20rpx;">
								<view><radio value=1 :checked="1==setFormData.partitionMode" /></view>
								<view>分区</view>
							</label>
						</radio-group>
					</view>
				</view>
				
				<view class="popup_group_item" v-if="isPlatformAdmin" @click="configDev()">
					<view class="popup_group_item_label">设备配置</view>
					<view class="popup_group_item_value">
						<view><span class="iconfont">&#xe6bd;</span></view>
					</view>
				</view>
				
			</view>

			<view class="popup_group" v-if="setFormData.partitionMode==0">
				<view class="popup_group_item" @click="jumpPartition(null, 0)">
					<view class="popup_group_item_label">钓塘设置</view>
					<view class="popup_group_item_value">
						<view><span class="iconfont">&#xe6bd;</span></view>
					</view>
				</view>
				<view class="popup_group_item" v-if="isPlatformAdmin">
					<view class="popup_group_item_label">钓位数量</view>
					<view class="popup_group_item_value">
						<input v-model="setFormData.seatCount" :disabled="!isPlatformAdmin" type="number" maxlength="3" placeholder="钓位数量" />
					</view>
				</view>
			</view>
			<view class="popup_group" v-else>
				<view style="display: flex; align-items: center;" v-for="(item, index) in setFormData.partitions" :key="index">
					<view class="popup_group" style="flex:4">
						<view class="popup_group_item">
							<view class="popup_group_item_label" style="width: 100rpx;">起始</view>
							<view class="popup_group_item_value">
								<input v-model="item.seatFrom" type="number" maxlength="3" placeholder="分区开始钓位" />
							</view>
						</view>
						
						<view class="popup_group_item">
							<view class="popup_group_item_label" style="width: 100rpx;">结束</view>
							<view class="popup_group_item_value">
								<input v-model="item.seatTo" type="number" maxlength="3" placeholder="分区结束钓位" />
							</view>
						</view>
					</view>
					<view class="popup_group" style="display: flex; flex-direction:column; flex:2">
						<!-- <view class="popup_group_item" style="align-items: center;" @click="jumpPartition(item.name, index)">
							<view class="popup_group_item_label">{{item.name}}设置</view>
						</view> -->
						<button class="mini-btn" type="warn" @click="jumpPartition(item.name, index)" style="margin:30rpx; padding: 10rpx; ">{{item.name}}设置</button>
						<button class="mini-btn" type="warn" :disabled="index<2" @click="delPartition(item.name)" style="margin:30rpx; padding: 10rpx; ">删除</button>
					</view>
					<!-- <view class="popup_group" style="flex:1">
						<view class="popup_group_item" @click="jumpPartition(item.name, index)">
							<view class="popup_group_item_value">
								<view><span class="iconfont">&#xe6bd;</span></view>
							</view>
						</view>
					</view> -->
				</view>
				<view class="popup_group_item" style="display: flex; justify-content: center;">
					<button class="mini-btn" type="warn" size="mini" @click="addPartition">添加分区</button>
				</view>
			</view>	


			<view class="input_content">
				<view class="input_content_describe" style="border-top: 0px;">
					<view class="input_content_describe_title">
						<view class="input_content_describe_title_msg">简介</view>
						<view class="input_content_describe_title_num">
							<text v-if="setFormData.store_info">{{ setFormData.store_info.length }}</text>
							<text v-else>0</text>
							/200
						</view>
					</view>
					<view class="input_content_describe_textarea">
						<textarea v-model="setFormData.store_info" value="" placeholder="请填写鱼种等简介信息" placeholderClass="placeholderClass" maxlength="200" />
					</view>
				</view>
				
				<view class="photo_count">
					<text class="photo_size">添加主图和轮播图，第1张作为主图。建议：图片尺寸为750*750px</text>
					<view class="input_content_photo">
						<view class="input_content_photo_adPh" v-for="(item, index) in setFormData.imageList" :key="index">				
							<image :src="item" class="myimg2 photos"></image>  			
							<view class="input_content_photo_adPh_jiao" @click="deleteImage(index)"><image src="../static/images/close.png" mode=""></image></view>
						</view>
						<view v-if="setFormData.imageList.length < 9" class="input_content_photo_adPh addBtn" @click="clk">
							<view><image src="../static/images/creamer.png" mode="widthFix"></image></view>
							<view>添加图片</view>
						</view>
					</view>
				</view>
			</view>			
		</view>

		<!-- 隐藏商品详情和视频
		<view class="content_list">
			<view class="content_list_item" @click="inputGoodsDetils">
				<view>商品详情</view>
				<view class="content_list_item_han">
					<span v-if="disModel" style="color: #000000">去修改</span>
					<span v-else>设置详情</span>
					<span class="iconfont">&#xe6bd;</span>
				</view>
			</view>
			<view class="content_list_video">
				<view class="content_list_video_title">商品视频</view>
				<view class="video_list">
					<view class="video_list_item photo" v-if="setFormData.video_link">
						<view class="jiao" @click="deleteVideo()">
							<video :src="setFormData.video_link"></video>
							<image src="../static/images/close.png" mode="widthFix"></image>
						</view>
					</view>
					<view class="photo" @click="uploadVideo" v-else>
						<view><image src="../static/images/creamer.png" mode="widthFix"></image></view>
						<view>添加视频</view>
					</view>
				</view>
			</view>
		</view>
		-->
		
		<view class="container_input">
			<view class="container_input_item">
				<view class="container_input_item_label"><span>是否推荐</span></view>
				<view class="container_input_item_value"><switch :checked="setFormData.is_good == 1" color="#E93323" style="transform:scale(0.8)" @change="isGood" /></view>
			</view>
			<!--
			<view class="container_input_item">
				<view class="container_input_item_label"><span>限购数量</span></view>
				<view class="container_input_item_value">
					<input v-model="setFormData.once_count" type="number" value="" placeholder="请输入限购数量" placeholder-class="inputPlaceHolder" />
				</view>
			</view>
			-->
			<view class="container_input_item">
				<view class="container_input_item_label"><span>商品排序</span></view>
				<view class="container_input_item_value">
					<input v-model="setFormData.sort" type="number" value="" placeholder="请输入商品排序" placeholder-class="inputPlaceHolder" />
			</view>
			</view>
		</view>
		
		<view class="handle dobuButton">
			<view class="handle_button" @click="doSubmit">提交</view>
		</view>
		
		<avatar @upload="doUpload" quality="1" ref="avatar" selWidth="250upx" selHeight="250upx"></avatar>
	</view>
</template>

<script>
const app = getApp();
import inputGoodsDetils from '../components/inputGoodsDetils.vue';
import linkageAssembly from '../components/linkageAssembly.vue';
import { navigateTo, serialize, setStorage, getStorage, removeStorage, Loading, hideLoading, Modal } from '../../../libs/uniApi.js';
import { categoryBrandlist, categorySelect, categoryList, attrList, templateList, productDetail, getDeliveryType } from '@/api/product.js';
import attr from '../components/attr.vue';
import platfrom from '../components/platform.vue';
import storeClassification from '../components/store_classification.vue';
import secound from './secound.vue';
import avatar from "@/components/yq-avatar/yq-avatar.vue";
import {TOKENNAME, HTTP_REQUEST_URL} from '@/config/app.js';
import store from '@/store';
import { productCreate, productUpdate } from 'api/product.js';
import {genDefaultPartition, correctSeats, MyTip, genDefaultSeat} from '../../../components/ssty/common.js';
export default {
	components: {
		inputGoodsDetils,
		linkageAssembly,
		attr,
		platfrom, // 选择平台分类组件
		storeClassification,
		secound,
		avatar
	},
	data() {
		let p1 = genDefaultPartition('1区', 1, 1, 1, 1, 1, 1.0);
		let p2 = genDefaultPartition('2区', 1, 1, 1, 2, 2, 1.0);
		
		return {
			isPlatformAdmin: app.globalData.isPlatformAdmin,
			merId: '',
			product_id: '', // 商品Id
			disModel: false,
			upload_max: 10,
			uploadUrl: `${HTTP_REQUEST_URL}/api/upload/video`,
			setFormData: {
				imageList: [],
				image: '', //主图
				slider_image: '', // 轮播图
                store_code: '', // 商品代码
				store_name: '', // 商品名
				store_info: '', // 简介
				
				is_good: 0, // 是否推荐
				is_gift_bag: 0,
				sort: '',
				once_count: '1', // 限购数量
				video_link: '',
				
				seatCount:1,			// 钓位数量
				partitionMode: 0, 		// 0-不分区，1-分区
				maxWeightPerFsh: '',	// 每条鱼最大重量（斤）
				minWeightPerFsh: '',	// 每条鱼最小重量（斤）
				partitions:[			// partitionMode=1时有效
					p1,
					// p2
				], 
			},
		};
	},
	computed: {
	},
	updated() {
	    console.log('ypIndex::updated, setFormData:%o', this.setFormData);
	},
	onLoad(opt) {
		this.merId = opt.mer_id;
		this.product_id = opt.product_id;

		if(getStorage('goodsDis')) { // 商品详情和普通商品共用一个页面
			this.disModel = true;
		}
		delete app.globalData.ypSeats;
		if (this.product_id) 
			this.loadDataFromSrv(); 	// 编辑
		else
			this.loadDataFromStorage(); // 新建
	},
	onShow() {
		if(app.globalData.ypPartition) {
			// 刚从partition页面返回的情况
			let idx = app.globalData.ypPartition.index;
			this.setFormData.partitions[idx] = app.globalData.ypPartition.partition;
			// if(app.globalData.ypPartition.partition.seatTo && app.globalData.ypPartition.partition.seatFrom)
			// 	this.setFormData.seatCount = app.globalData.ypPartition.partition.seatTo - app.globalData.ypPartition.partition.seatFrom + 1;
			delete app.globalData.ypPartition;
			console.log("ypIndex::onShow| config partition return, index=%o, value=%o", idx, this.setFormData.partitions[idx]);
		}
		
		if(app.globalData.ypSeats && app.globalData.ypSeats.length > 0){
			let countIndex = 0;
			for(let i = 0; i < this.setFormData.partitions.length; i++) {
				for(let o = 0; o < this.setFormData.partitions[i].seats.length; o++) {
					this.setFormData.partitions[i].seats[o] = app.globalData.ypSeats[countIndex];
					countIndex++;
				}
			}
		}
		
		
		if(this.step == 2) {
			this.secoundModel = !this.secoundModel;
		}	
	},

	watch: {
		setFormData: {
			handler(val) {
				console.log("watch setFormData: %o", val);
				setTimeout(()=>{
					setStorage('addGoodsFormData', this.setFormData);
				});
			},
			deep: true
		},
		'setFormData.imageList'(val) {
			this.setFormData.image = val.length ? val[0] : '';
			this.setFormData.slider_image = val.length ? serialize(val).splice(1) : [];
		}
	},
	methods: {
		
		// 获取数据
		async loadDataFromStorage() {
			var that = this;
			if (getStorage('addYpFormData')) {
				this.setFormData = getStorage('addYpFormData');
				that.processSeats();
			}
		},
		// 查询详情数据
		loadDataFromSrv() {
			var that = this;
			Loading();
			
			if(getStorage('editYpFormData')) {
				removeStorage('editYpFormData'); 
			}
			
			productDetail(this.merId, this.product_id).then(res => {
				setStorage('editYpFormData', res.data);
				let editYpFormData = res.data;
				Object.keys(this.setFormData).forEach(item => {
					this.setFormData[item] = editYpFormData[item];
				});
				this.setFormData.product_id = this.product_id;
				this.setFormData.imageList = [...(this.setFormData.image ? [this.setFormData.image] : []), ...this.setFormData.slider_image];
				
				this.setFormData.store_code = res.data.yp.code;
				this.setFormData.seatCount = parseInt(res.data.yp.seatNumber);
				this.setFormData.partitionMode = res.data.yp.partitionMode;
				this.setFormData.maxWeightPerFsh = res.data.yp.maxWeightPerFsh;
				this.setFormData.minWeightPerFsh = res.data.yp.minWeightPerFsh;
				this.setFormData.partitions = res.data.yp.partitions;
				that.processSeats();
				if(res.data.content && (res.data.content.title || res.data.content.image)) {
					setStorage('goodsDis', {store_name: res.data.content.title, imageList:res.data.content.image});
					this.disModel = true;
				}
				
				hideLoading();
			}).catch(e => {
				console.error("loadDataFromSrv", e);
				hideLoading();
				MyTip('加载鱼塘失败，请稍后重试');
			});
		},
		onpartitionModeChange(e) {
			let newMode = parseInt(e.detail.value);
			this.setFormData.partitionMode = newMode;
			// console.log('ypIndex::onpartitionModeChange, e=%o, partitionMode=%o', e, this.setFormData.partitionMode);
			if(newMode == 1) {
				if(this.setFormData.partitions.length < 2){
					this.addPartition();
				}
			}
			this.processSeats();
		},
		jumpPartition(name, index) {
			this.processSeats();
			if(!this.checkSeats())return;
			let partitionMode = this.setFormData.partitionMode;
			let seatCount = parseInt(this.setFormData.seatCount);
			if(this.setFormData.partitionMode == 1) { // 有分区
				let partition = this.setFormData.partitions.find(item=>item.name == name);
				let otherPartitions = this.setFormData.partitions.filter(item=>item.name != name);
				// crmeb在页面间跳转的传参用的是storage，我用globaleData
				app.globalData.ypPartition = {partitionMode, seatCount, index, partition, otherPartitions}; 
			}
			else { // 无分区
				let partition = this.setFormData.partitions[0];
				let otherPartitions = [];
				app.globalData.ypPartition = {partitionMode, seatCount, index, partition, otherPartitions}; 
			}
			navigateTo(1, '/pages/product/addGoods/ypPartition');
		},
		checkSeats() {
			if(this.setFormData.partitionMode == 1) {
				let seatNoCkGlo = 0;
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					if(this.setFormData.partitions[i].seatFrom*1 != seatNoCkGlo+1){
						MyTip(seatNoCkGlo+"号座位配置异常(起始)");
						return false;
					}
					for(let o = 0; o < this.setFormData.partitions[i].seats.length; o++) {
						seatNoCkGlo++;
						if(this.setFormData.partitions[i].seats[o].seatNo!=seatNoCkGlo) {
							MyTip(seatNoCkGlo+"号座位配置异常(中位)");
							return false;
						}
					}
				}
				if(this.setFormData.partitions[this.setFormData.partitions.length-1].seatTo*1 != seatNoCkGlo){
					MyTip(seatNoCkGlo+"号座位配置异常(结束)");
					return false;
				}
			}
			return true;
		},
		processSeats() {
			if(this.setFormData.partitionMode == 1) {
				let ck = 0;
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					ck++;
					if(this.setFormData.partitions[i].seatFrom*1 != ck){
						MyTip(this.setFormData.partitions[i].name+"需保持位置配置连贯，且覆盖全部钓位");
						return;
					}
					ck = this.setFormData.partitions[i].seatTo*1;
				}
				if(ck != this.setFormData.seatCount*1){
					MyTip("分区钓位与座位数不匹配");
					return;
				}
			}
			
			app.globalData.ypSeats = [];
			//抽取所有的座位
			let tmpSeats = [];
			for(let i = 0; i < this.setFormData.partitions.length; i++) {
				for(let o = 0; o < this.setFormData.partitions[i].seats.length; o++) {
					tmpSeats.push(this.setFormData.partitions[i].seats[o]);
				}
				let l = this.setFormData.partitions[i].seats.length;
				for(let o = l-1; o >= 0; o--) {
					this.setFormData.partitions[i].seats.splice(o,1)
				}
			}
			app.globalData.ypSeats = tmpSeats.sort(this.compare('seatNo', true))
			if(this.setFormData.partitionMode == 1) {
				
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					if(parseInt(this.setFormData.partitions[i].seatFrom)==NaN || parseInt(this.setFormData.partitions[i].seatTo)==NaN){
						return MyTip("请完善分区范围");
					}
					if(parseInt(this.setFormData.partitions[i].seatFrom) > parseInt(this.setFormData.partitions[i].seatTo)){
						return MyTip("请输入正确的分区范围");
					}
					for(let o = parseInt(this.setFormData.partitions[i].seatFrom); o < parseInt(this.setFormData.partitions[i].seatTo)+1; o++){
						if(app.globalData.ypSeats[o-1]){
							this.setFormData.partitions[i].seats.push(app.globalData.ypSeats[o-1]);
						}else{
							this.setFormData.partitions[i].seats.push(genDefaultSeat(o));
						}
					}
				}
			}else{
				let l = this.setFormData.partitions.length;
				for(let i = l-1; i > 0; i--) {
					this.setFormData.partitions.splice(i,1)
				}
				for(let i = 0; i < this.setFormData.seatCount; i++) {
					if(app.globalData.ypSeats[i]){
						this.setFormData.partitions[0].seats.push(app.globalData.ypSeats[i]);
					}else{
						this.setFormData.partitions[0].seats.push(genDefaultSeat(i*1+1));
					}
				}
			}
			app.globalData.ypSeats = [];
			//抽取所有的座位
			tmpSeats = [];
			for(let i = 0; i < this.setFormData.partitions.length; i++) {
				for(let o = 0; o < this.setFormData.partitions[i].seats.length; o++) {
					tmpSeats.push(this.setFormData.partitions[i].seats[o]);
				}
			}
			app.globalData.ypSeats = tmpSeats.sort(this.compare('seatNo', true))
			
			
			
			
			// app.globalData.ypSeats = [];
			// let seatCount = 0;
			// let lastID = 0;
			// for(let i = 0; i < this.setFormData.partitions.length; i++) {
			// 	for(let o = 0; o < this.setFormData.partitions[i].seats.length; o++) {
			// 		app.globalData.ypSeats.push(this.setFormData.partitions[i].seats[o]);
			// 	}
			// 	this.setFormData.partitions[i].seats = [];
			// 	seatCount += this.setFormData.partitions[i].seatTo - this.setFormData.partitions[i].seatFrom + 1;
			// 	if(this.setFormData.partitionMode == 1) {
			// 		lastID = this.setFormData.partitions[i].seatTo;
			// 	}
			// }
			// let moreSeats = 0;
			// if(this.setFormData.partitionMode == 1) {
			// 	moreSeats = seatCount - app.globalData.ypSeats.length;
			// 	this.setFormData.seatCount = seatCount;
			// 	lastID++;
			// }else{
			// 	moreSeats = this.setFormData.seatCount - app.globalData.ypSeats.length;
			// 	lastID = app.globalData.ypSeats.length*1+1
			// }
			// if(moreSeats > 0){
			// 	for(var i = 0; i < moreSeats; i++)
			// 	{
			// 		app.globalData.ypSeats.push(genDefaultSeat(lastID*1+i))
			// 	}
			// }else if(moreSeats < 0){
			// 	let delSeats = app.globalData.ypSeats.length-seatCount;
			// 	for(var i =0; i < delSeats; i++)
			// 	{
			// 		app.globalData.ypSeats.splice(app.globalData.ypSeats.length-1,1)
			// 	}
			// }
			// if(this.setFormData.partitionMode == 1) {
			// 	if(app.globalData.ypSeats && app.globalData.ypSeats.length > 0){
			// 		let singleNum = Math.ceil(app.globalData.ypSeats.length / this.setFormData.partitions.length);
			// 		let countIndex = 0;
			// 		let seatIndex = 1;
			// 		if(this.setFormData.partitions.length>1){
						
			// 		}else{
			// 			for(let i = 0; i < this.setFormData.partitions.length; i++) {
			// 				this.setFormData.partitions[i].seatFrom = seatIndex;
			// 				for(let o = 0; o < singleNum; o++) {
			// 					if(app.globalData.ypSeats[countIndex]){
			// 						this.setFormData.partitions[i].seats.push(app.globalData.ypSeats[countIndex]);
			// 						countIndex++;
			// 						this.setFormData.partitions[i].seatTo = seatIndex;
			// 						seatIndex++;
			// 					}
			// 				}
			// 			}
			// 		}
			// 	}
			// }else{
			// 	this.setFormData.partitions[0].seats = app.globalData.ypSeats;
			// 	this.setFormData.partitions[0].seatFrom = 1;
			// 	this.setFormData.partitions[0].seatTo = this.setFormData.seatCount;
			// 	for(let i = 1; i < this.setFormData.partitions.length; i++) {
			// 		this.setFormData.partitions.splice(i,1)
			// 	}
			// }
		},
		configDev() {
			this.processSeats();
			if(!this.checkSeats())return;
			navigateTo(1, '/pages/product/addGoods/ypSeat');
		},
		addPartition() {
			// 指定一个唯一的名称
			let name;
			for(let i = this.setFormData.partitions.length; i < 100; i++) {
				name = i+'区';
				if(!this.setFormData.partitions.find(a=>a.name == name))
					break;
			}
			let pricePartition = (this.setFormData.partitions[0] && this.setFormData.partitions[0].prices[0] && this.setFormData.partitions[0].prices[0].price) ? this.setFormData.partitions[0].prices[0].price : 1.0;
			this.setFormData.partitions.push(genDefaultPartition(name, 1, 1, 1, false, false, pricePartition));
		},
		delPartition(name) {
			this.setFormData.partitions.splice(this.setFormData.partitions.findIndex(a=>a.name==name), 1);
		},
		
		// 选择图片
		handleChooseImage() {
			let that = this;
			that.$util.uploadImageOne('upload/image', function(res) {
				that.setFormData.imageList.push(res.data.path);
				
			});
		},
		clk() {
			let avatar = this.$refs.avatar;
			avatar.fChooseImg(1,{selWidth: '350upx', selHeight: '350upx', inner: true});
		},
		doUpload(rsp) {
			let that = this
			console.log(rsp);	
			
		
			uni.uploadFile({
				url: HTTP_REQUEST_URL + '/api/upload/image/field',
				filePath: rsp.path,
				name: 'field',
				formData: {
					'filename': rsp.path
				},
				header: {
					// #ifdef MP
					"Content-Type": "mulMyTipart/form-data",
					// #endif
					[TOKENNAME]: 'Bearer ' + store.state.app.token
				},
				success: (uploadFileRes) => {
					console.log(uploadFileRes.data);
					let imgData = JSON.parse(uploadFileRes.data)
					that.setFormData.imageList.push(imgData.data.path)
				},
				complete(res) {
					console.log(res)
				}
			});		
		},
		// 删除图片
		deleteImage(index) {
			this.setFormData.imageList.splice(index, 1);
		},
		
		// 是否推荐
		isGood(e) {
			this.setFormData.is_good = e.detail.value ? 1: 0;
		},
		// 是否开启礼包
		isGiftBag(e) {
			this.setFormData.is_gift_bag = e.detail.value ? 1: 0;
		},
		
		switchChange(value, item) {
			this.setFormData[item.model] = value ? 1 : 0;
		},
		// 跳转商品详情
		inputGoodsDetils() {
			navigateTo(1, '/pages/product/addGoods/addGoodDetils', { mer_id: this.merId });
		},
		// 上传视频
		uploadVideo() {
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				success: res => {
					if (Math.ceil(res.size / 1024) < this.upload_max * 1024) {
						uni.uploadFile({
							url: this.uploadUrl, //仅为示例，非真实的接口地址
							filePath: res.tempFilePath,
							name: 'file',
							//请求参数
							formData: {
								user: 'test'
							},
							header: {
								// #ifdef MP
								'Content-Type': 'mulMyTipart/form-data',
								// #endif
								[TOKENNAME]: 'Bearer ' + store.state.app.token
							},
							success: uploadFileRes => {
								let data = JSON.parse(uploadFileRes.data);
								this.setFormData.video_link = (data.data.src);
							},
							complete: a => {
								// console.log(a);
							}
						});
					} else {
						uni.showModal({
							title: '提示',
							content: `视频超出限制${this.upload_max}MB,已过滤`
						});
					}
				},
				fail: err => {
					uni.showModal({
						content: JSON.stringify(err)
					});
				}
			});
		},
		deleteVideo(index) {
			this.setFormData.video_link = '';
		},
		
		check() {
			console.log("check, setFormData: %o", this.setFormData)
			
			let requireData = {
				image: '请选择主图', 
                //store_code: '请输入商代码',
				store_name: '请输入商品名',
				// 修改分区钓位允许重叠 seatCount: '请输入钓位数量', 
			};
			if(Object.keys(requireData).some(item => {
				if (!this.setFormData[item]) {
					MyTip(requireData[item]);
					return true;
				}
			}))
				return;
			
			if(this.setFormData.partitionMode == 0) {
				if(!this.setFormData['seatCount']) {
					MyTip('请输入钓位数量');
					return false;
				}
				
				this.setFormData.partitions = this.setFormData.partitions.slice(0, 1);
				this.setFormData.partitions[0].seatFrom = 1;
				this.setFormData.partitions[0].seatTo = parseInt(this.setFormData.seatCount);
				
				// 修正seats配置
				correctSeats(this.setFormData.partitions[0].seats, this.setFormData.partitions[0].seatFrom, this.setFormData.partitions[0].seatTo);
			}
			else {
				// 检查分区名称必须唯一
				let names = this.setFormData.partitions.map(a=>a.name);
				if(new Set(names).size != names.length) {
					MyTip('分区名称存在相同的，请重新修改分区配置');
					canJumpFlag = false;
				}
				let ck = 0;
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					ck++;
					if(this.setFormData.partitions[i].seatFrom*1 != ck){
						MyTip(this.setFormData.partitions[i].name+"需保持位置配置连贯，且覆盖全部钓位");
						return;
					}
					ck = this.setFormData.partitions[i].seatTo*1;
				}
				if(ck != this.setFormData.seatCount*1){
					MyTip("分区钓位与座位数不匹配");
					return;
				}
					
				// begin 修改分区钓位允许重叠
				/*
				// 检查分区钓位数量之和<=鱼塘钓位
				let sum = this.setFormData.partitions.reduce((sum,a)=>{sum+=a.seatCount}, 0);
				if(sum > this.setFormData.seatCount) {
					MyTip('分区钓位数量之和超过了鱼塘总钓位数，请重新修改分区配置');
					return;
				}
			
				// 检查分区钓位起止位置不能重叠
				let overlap = false;
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					let a = this.setFormData.partitions[i];
					let aSeatFrom = parseInt(a.seatFrom), aSeatTo = parseInt(a.seatTo);
					this.setFormData.partitions[i].seatFrom = aSeatFrom;
					this.setFormData.partitions[i].seatTo = aSeatTo;
					
					for(let j = 0; j < this.setFormData.partitions.length; j++) {
						if(i == j)
							continue;
						let b = this.setFormData.partitions[j];
						let bSeatFrom = parseInt(b.seatFrom), bSeatTo = parseInt(b.seatTo);
						if(aSeatFrom >= bSeatFrom && aSeatFrom <= bSeatTo) {
							overlap = true;
							break;
						}
						if(aSeatTo >= bSeatFrom && aSeatTo <= bSeatTo) {
							overlap = true;
							break;
						}
					}
					if(overlap)
						break;
				}
				if(overlap) {
					MyTip('分区钓位起止位置有重叠的，请重新修改分区配置');
					return;
				}*/
				// let seatCount = 0;
				// for(let i = 0; i < this.setFormData.partitions.length; i++) {
				// 	let a = this.setFormData.partitions[i];
				// 	let aSeatFrom = parseInt(a.seatFrom), aSeatTo = parseInt(a.seatTo);
				// 	this.setFormData.partitions[i].seatFrom = aSeatFrom;
				// 	this.setFormData.partitions[i].seatTo = aSeatTo;
				// 	seatCount += aSeatTo - aSeatFrom + 1;
				// }
				// this.setFormData.seatCount = seatCount;
				// end 
			}
			
			// 检查分区配置
			if(this.setFormData.partitions.some((a, index)=>{  	// ES6中数组方法：some一真即真，every  一假即假
				if(this.setFormData.partitionMode == 0 && index > 0)
					return false;
					
				if(a.allowChangeSeat==1) {
					//最低一元
					if(parseFloat(a.changeSeatPrice) < 1) {
						MyTip(a.name+'换位价格配置无效');
						return true;
					}
				}
				
				if(this.setFormData.partitionMode == 1) {
					if(!a.seatFrom) {
						MyTip(a.name+'起始钓位配置无效');
						return true;
					}
					if(!a.seatTo) {
						MyTip(a.name+'结束钓位配置无效');
						return true;
					}
				}
				
				let name = (this.setFormData.partitionMode == 0)?(this.setFormData.name?this.setFormData.name:'鱼塘'):a.name;
				if(a.prices.some(b=>{
					if(!b.price) {
						MyTip(name+'价格配置无效');
						return true;
					}
					if(!b.retPrice) {
						// MyTip(name+'回鱼价格配置无效');
						// return true;
						b.retPrice = 0.0; // 允许回鱼价格为0
					}
					if(a.timeMode==1) {
						if(!b.startTime) {
							MyTip(name+'时段开始时间配置无效');
							return true;
						}
						if(!b.endTime) {
							MyTip(name+'时段结束时间配置无效');
							return true;
						}
					}
					else {
						if(!b.duration) {
							MyTip(name+'时长配置无效');
							return true;
						}
					}
				}))
					return true;
				
				// 检查是否有重复时间配置
				for(let i = 0; i < a.prices.length; i++) {
					let i_name = a.prices[i].name; // 有指定名称则优先使用名称
					if(!i_name) { 
						i_name = a.timeMode==1?(a.prices[i].startTime+"~"+a.prices[i].endTime):(a.prices[i].duration+"");
					}
					
					for(let j = 0; j < a.prices.length; j++) {
						if(j == i) 
							continue;
						
						let j_name = a.prices[j].name; // 有指定名称则优先使用名称
						if(!j_name) { 
							j_name = a.timeMode==1?(a.prices[j].startTime+"~"+a.prices[j].endTime):(a.prices[j].duration+"");
						}
						
						if(i_name == j_name) {
							MyTip('时间或名称配置重复：'+i_name);
							return true;
						}
					}
				}
				
				if(a.seats.some(c=>{
					if(c.useDevice && !c.deviceSn) {
						MyTip(name+'第'+c.seatNo+'号钓位指定了使用设备，但没选择设备');
						return true;
					}
				}))
					return true;
			})) 
				return;
			
			return true;
		},
		
		doSubmit() {
			this.processSeats();
			if(!this.checkSeats())return;
			if(!this.check()) {
				return;
			}
			this.setFormData.maxWeightPerFsh = parseFloat(this.setFormData.maxWeightPerFsh);
			this.setFormData.minWeightPerFsh = parseFloat(this.setFormData.minWeightPerFsh);
			
			let waitDeleteData = ['addYpFormData', 'editYpFormData', 'goodsDis']; // 提交后就把本地缓存数据清空
				
			let postData = {
				...getStorage('addGoodsFormData'),
				...this.setFormData,
				content: {
					title: getStorage('goodsDis') ? getStorage('goodsDis').store_name : '',
					image: getStorage('goodsDis') ? getStorage('goodsDis').imageList : []
				},
				video_link: this.setFormData.video_link,
				cate_id: app.globalData.fish_cate,
			};
			
			
			if (this.product_id) {
				console.log("postData",postData)
				uni.showLoading({
					title: '正在修改中...'
				});
				productUpdate(this.merId, this.product_id, postData)
					.then(res => {
						hideLoading()
						waitDeleteData.forEach(item => {
							if (getStorage(item)) {
								removeStorage(item);
							}
						});
						
						console.log("ypIndex::doSubmit| productUpdate success");
						Modal('提交成功，等待平台审核', '点击确定，返回商品管理', {
							showCancel: false
						}).then(() => {
						uni.redirectTo({
							url:'/pages/product/goodsOnSale/index?mer_id=' + this.merId
						})
						})
					})
					.catch(errMsg => {
						uni.hideLoading();
						console.log("ypIndex::doSubmit| productUpdate fail", errMsg);
						MyTip(errMsg);
					});
			} else {
				uni.showLoading({
					title: '正在创建中...'
				});
				productCreate(this.merId, postData)
					.then(res => {
						hideLoading();
						
						waitDeleteData.forEach(item => {
							if (getStorage(item)) {
								removeStorage(item);
							}
						});
						
						console.log("ypIndex::doSubmit| productCreate success");
						Modal('提交成功，等待平台审核', '点击确定，返回商品管理', {
							showCancel: false,
						}).then(() => {
							uni.redirectTo({
								url:'/pages/product/goodsOnSale/index?mer_id=' + this.merId
							})
						})
					})
					.catch(errMsg => {
						hideLoading();
						console.log("ypIndex::doSubmit| productCreate false", errMsg);
						MyTip(errMsg);
					});
			}
		},
		
		compare(attr,rev) {
			// console.log(attr, rev)
			if(rev ==  undefined){
			  rev = 1;
			}else{
			  rev = (rev) ? 1 : -1;
			}
			return (a,b) => {
			  a = a[attr];
			  b = b[attr];
			  if(a < b){
				  return rev * -1;
			  }
			  if(a > b){
				  return rev * 1;
			  }
			  return 0;
			}
		},

	}
};
</script>

<style lang="scss" scoped>
@import './scss/index.scss';


.content_list {
	width: 710rpx;
	margin: auto;
	padding: 0 20rpx;
	box-sizing: border-box;
	background: #fff;
	margin-top: 31rpx;
	border-radius: 10rpx;
	.content_list_item {
		padding: 32rpx 10rpx;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
		.content_list_item_han {
			color: #bbbbbb;
			display: flex;
			align-items: center;
		}
	}
	.content_list_video {
		min-height: 154rpx;
		padding: 23rpx 10rpx;
		display: flex;
		justify-content: space-between;
		.content_list_video_title {
			padding-top: 10rpx;
		}

		.video_list {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			flex-wrap: wrap;
		}
	}
}

.photo {
	border: 1px solid #dddddd;
	opacity: 1;
	border-radius: 8rpx;
	font-size: 28rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	text-align: center;
	// padding: 27rpx 21rpx 24rpx 21rpx;
	width: 150rpx;
	height: 150rpx;
	box-sizing: border-box;
	color: #bbbbbb;
	margin-left: 16rpx;
	position: relative;
	margin-bottom: 12rpx;
	image {
		width: 62rpx;
		margin-bottom: 10rpx;
	}
}

.jiao {
	image {
		position: absolute;
		top: -14rpx;
		right: -14rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		padding: 8rpx;
		background: #e93323;
		z-index: 999;
	}
	video {
		width: 150rpx;
		height: 150rpx;
	}
}
.container_input {
	background: #fff;
	padding: 0 20rpx;
	width: 710rpx;

	margin: auto;
	margin-top: 31rpx;
	border-radius: 10rpx;
	&_item {
		display: flex;
		height: 106rpx;
		align-items: center;
		.select_and_input {
			display: flex;
			align-items: center;
			justify-content: space-between;
			.greyColor {
				color: #bbbbbb;
			}
		}

		.radio {
			padding: 30rpx 0;
		}

		&_label {
			padding-left: 10rpx;
			color: #333333;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			.select_check {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 40rpx;
				height: 40rpx;
				border: 1px solid #cccccc;
				border-radius: 50%;
				margin-right: 20rpx;

				.iconfont {
					font-size: 24rpx;
				}
			}

			.select {
				background: #e93323;
				border: none;
				.iconfont {
					color: #fff;
				}
			}
		}
		&_value {
			padding-right: 10rpx;
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			> span:nth-child(1) {
				display: inline-block;
				margin-right: 15rpx;
			}
			.text {
				color: #000;
				display: inline-block;
				max-width: 400rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			input {
				text-align: right;
			}

			.select_group {
				display: flex;
			}

			&_select {
				display: flex;
				margin-right: 110rpx;
			}
		}

		.flex_start {
			padding: 0 10rpx;
			margin-top: 40rpx;
			justify-content: flex-start;
		}
	}
	> view:not(:last-child) {
		border-bottom: 1px solid #eeeeee;
	}
}

.inputPlaceHolder {
	color: #bbbbbb;
}

.paddingTop_none {
	padding-top: 0 !important;
}
.marginTop_none {
	margin-top: 0;
}

</style>
